<template>
  <div class="pager-container">
      <a :class="{disabled: current === 1}" @click="handleClick(1)">首页</a>
      <a :class="{disabled: current === 1}" @click="handleClick(current-1)">上一页</a>
      <a v-for="(n, i) in numbers" :key="i"
        :class="{active: n == current}"
        @click="handleClick(n)"
       >
          {{n}}
      </a>
      <a :class="{disabled: current === pageNumber}" @click="handleClick(current+1)">下一页</a>
      <a :class="{disabled: current === pageNumber}" @click="handleClick(pageNumber)">末页</a>
  </div>
</template>

<script>
export default {
    props: {
        // 当前页码
        current: {
            type: Number,
            default: 1
        },
        // 总数据量
        total: {
            type:Number,
            default: 0
        },
        // 页容量   
        limit: {
            type: Number,
            default: 10
        },
        // 可见页码数
        visibleNumber: {
            type:Number,
            default:10
        }
    },
    computed: {
        // 总页码
        pageNumber(){
            return Math.ceil(this.total/this.limit)
        },
        // 当前最小页码
        visibleMin(){
            let min = this.current - Math.floor(this.visibleNumber /2);
            if(min<1) {
                min = 1;
            }
            return min;
        },
        // 当前最大页码
        visibleMax(){
            let max = this.visibleMin + this.visibleNumber -1;
            if(max > this.pageNumber) {
                max = this.pageNumber
            }
            return max;
        },
        numbers() {
            let num = [];
            for (let i = this.visibleMin; i <= this.visibleMax; i++) {
                num.push(i)
            }
            return num;
        }
    },
    methods: {
        handleClick(newPage) {
            if(newPage<1) {
                newPage = 1
            }
            if(newPage>this.pageNumber) {
                newPage = this.pageNumber
            }
            if(newPage === this.current) {
                return;
            }
            this.$emit('pageChange', newPage);
        }
    }
}
</script>

<style lang="less" scoped>
@import "~@/styles/var.less";
.pager-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
  user-select: none;
  a {
    color: @primary;
    margin: 0 6px;
    cursor: pointer;
    &.disabled {
      color: @lightWords;
      cursor: not-allowed;
    }
    &.active {
      color: @words;
      font-weight: bold;
      cursor: text;
    }
  }
}
</style>